<template>
  <div class="user-management">
    <el-card shadow="hover" class="users-card">
      <!-- 搜索和过滤组件 -->
      <div class="filter-bar">
        <el-input
          v-model="userKeyword"
          placeholder="搜索用户"
          class="search-input"
          clearable
          @keyup.enter="getUserList"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-button type="primary" @click="getUserList">
          <el-icon><Search /></el-icon>查询
        </el-button>
      </div>
      
      <!-- 用户列表 -->
      <el-table
        v-loading="loading"
        :data="users"
        style="width: 100%; margin-top: 20px;"
        border
        @selection-change="handleUserSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="nickname" label="昵称" width="120" />
        <el-table-column prop="email" label="邮箱" width="180" />
        <el-table-column prop="role" label="角色" width="100">
          <template #default="scope">
            <el-tag :type="getUserRoleTag(scope.row.role)">
              {{ getUserRoleText(scope.row.role) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getUserStatusTag(scope.row.status)">
              {{ getUserStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="注册时间" width="180" />
        <el-table-column label="操作" fixed="right" width="250">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              plain
              @click="navigateToUserDetail(scope.row.id)"
            >查看</el-button>
            <el-button
              v-if="scope.row.status === 1"
              type="danger"
              size="small"
              plain
              @click="updateUserStatus(scope.row.id, 0)"
            >禁用</el-button>
            <el-button
              v-else
              type="success"
              size="small"
              plain
              @click="updateUserStatus(scope.row.id, 1)"
            >启用</el-button>
            <el-dropdown trigger="click" @command="(cmd) => handleUserRoleCommand(cmd, scope.row)">
              <el-button size="small" plain>
                角色<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item :command="1">普通用户</el-dropdown-item>
                  <el-dropdown-item :command="2">专家用户</el-dropdown-item>
                  <el-dropdown-item :command="3">管理员</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 批量操作 -->
      <UserBatchActions
        v-if="selectedUsers.length > 0"
        :count="selectedUsers.length"
        @batch-enable="batchUpdateUserStatus(1)"
        @batch-disable="batchUpdateUserStatus(0)"
        @batch-delete="batchDeleteUsers"
      />
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          background
          layout="total, sizes, prev, pager, next"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 用户统计 -->
    <UserStatistics :stats="userStats" @refresh="refreshStats" />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search, ArrowDown } from '@element-plus/icons-vue';
import { 
  getUserList as apiGetUserList, 
  updateUserStatus as apiUpdateUserStatus, 
  updateUserRole as apiUpdateUserRole, 
  batchDeleteUsers as apiBatchDeleteUsers,
  getUserStatistics
} from '../../api/admin';
import UserBatchActions from './UserBatchActions.vue';
import UserStatistics from './UserStatistics.vue';

const props = defineProps({});
const emit = defineEmits(['refresh']);
const router = useRouter();

// 用户管理相关
const users = ref([]);
const userKeyword = ref('');
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const selectedUsers = ref([]);
const loading = ref(false);
const userStats = ref(null);

// 获取用户列表
const getUserList = async () => {
  loading.value = true;
  try {
    const params = {
      current: currentPage.value,
      size: pageSize.value,
      keyword: userKeyword.value
    };
    
    const response = await apiGetUserList(params);
    if (response.code === 200) {
      users.value = response.data.records || [];
      total.value = response.data.total || 0;
    } else {
      ElMessage.error(response.message || '获取用户列表失败');
    }
  } catch (error) {
    console.error('获取用户列表失败:', error);
    ElMessage.error('获取用户列表失败: ' + (error.message || '未知错误'));
    users.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

// 获取用户统计数据
const getUserStatisticsData = async () => {
  try {
    const response = await getUserStatistics();
    if (response.code === 200) {
      userStats.value = response.data;
    } else {
      console.error('获取用户统计数据失败:', response.message);
    }
  } catch (error) {
    console.error('获取用户统计数据失败:', error);
  }
};

// 用户角色标签和文本
const getUserRoleTag = (role) => {
  const roles = {
    1: '',
    2: 'success',
    3: 'danger'
  };
  return roles[role] || '';
};

const getUserRoleText = (role) => {
  const roles = {
    1: '普通用户',
    2: '专家用户',
    3: '管理员'
  };
  return roles[role] || '未知';
};

// 用户状态标签和文本
const getUserStatusTag = (status) => {
  return status === 1 ? 'success' : 'danger';
};

const getUserStatusText = (status) => {
  return status === 1 ? '正常' : '禁用';
};

// 处理用户选择变化
const handleUserSelectionChange = (selection) => {
  selectedUsers.value = selection;
};

// 处理用户分页
const handleSizeChange = (val) => {
  pageSize.value = val;
  getUserList();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  getUserList();
};

// 更新用户状态
const updateUserStatus = async (id, status) => {
  if (!id) {
    ElMessage.warning('用户ID不存在，无法更新状态');
    return;
  }
  
  try {
    const statusText = status === 1 ? '启用' : '禁用';
    await ElMessageBox.confirm(`确定要${statusText}该用户吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    loading.value = true;
    const response = await apiUpdateUserStatus(id, status);
    if (response.code === 200) {
      ElMessage.success(`用户${statusText}成功`);
      getUserList();
    } else {
      ElMessage.error(response.message || `用户${statusText}失败`);
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('更新用户状态失败:', error);
      ElMessage.error('操作失败: ' + (error.message || '未知错误'));
    }
  } finally {
    loading.value = false;
  }
};

// 批量更新用户状态
const batchUpdateUserStatus = async (status) => {
  if (selectedUsers.value.length === 0) {
    ElMessage.warning('请选择要操作的用户');
    return;
  }
  
  try {
    const statusText = status === 1 ? '启用' : '禁用';
    await ElMessageBox.confirm(`确定要${statusText}选中的${selectedUsers.value.length}个用户吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    loading.value = true;
    const promises = selectedUsers.value.map(user => apiUpdateUserStatus(user.id, status));
    await Promise.all(promises);
    
    ElMessage.success(`已${statusText}${selectedUsers.value.length}个用户`);
    getUserList();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量更新用户状态失败:', error);
      ElMessage.error('操作失败: ' + (error.message || '未知错误'));
    }
  } finally {
    loading.value = false;
  }
};

// 处理用户角色下拉菜单命令
const handleUserRoleCommand = async (role, user) => {
  if (!user || !user.id) {
    ElMessage.warning('用户信息不存在，无法更新角色');
    return;
  }
  
  if (user.role === role) return;
  
  try {
    const roleText = getUserRoleText(role);
    await ElMessageBox.confirm(`确定要将用户"${user.username}"设置为"${roleText}"吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    loading.value = true;
    const response = await apiUpdateUserRole(user.id, role);
    if (response.code === 200) {
      ElMessage.success(`用户角色设置成功`);
      getUserList();
    } else {
      ElMessage.error(response.message || '用户角色设置失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('设置用户角色失败:', error);
      ElMessage.error('操作失败: ' + (error.message || '未知错误'));
    }
  } finally {
    loading.value = false;
  }
};

// 批量删除用户
const batchDeleteUsers = async () => {
  if (selectedUsers.value.length === 0) {
    ElMessage.warning('请选择要删除的用户');
    return;
  }
  
  try {
    await ElMessageBox.confirm(`确定要删除选中的${selectedUsers.value.length}个用户吗？此操作不可恢复！`, '警告', {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'error'
    });
    
    loading.value = true;
    const userIds = selectedUsers.value.map(user => user.id);
    const response = await apiBatchDeleteUsers(userIds);
    
    if (response.code === 200) {
      ElMessage.success(`已删除${response.data || selectedUsers.value.length}个用户`);
      getUserList();
      getUserStatisticsData(); // 更新统计数据
    } else {
      ElMessage.error(response.message || '批量删除用户失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除用户失败:', error);
      ElMessage.error('操作失败: ' + (error.message || '未知错误'));
    }
  } finally {
    loading.value = false;
  }
};

// 跳转到用户详情页
const navigateToUserDetail = (userId) => {
  if (!userId) {
    ElMessage.warning('用户ID不存在，无法查看');
    return;
  }
  
  try {
    // 跳转到用户主页
    router.push(`/user/${userId}`);
  } catch (error) {
    console.error('页面跳转失败:', error);
    ElMessage.error('页面跳转失败');
  }
};

// 初始化
onMounted(() => {
  getUserList();
  getUserStatisticsData();
});

// 刷新统计数据
const refreshStats = () => {
  getUserStatisticsData();
};

// 暴露方法给父组件
defineExpose({
  getUserList,
  getUserStatisticsData
});
</script>

<style scoped>
.user-management {
  width: 100%;
}

.users-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.filter-bar {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 20px;
}

.search-input {
  width: 250px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .filter-bar {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .search-input {
    width: 100%;
  }
  
  .filter-bar .el-button {
    margin-left: 0 !important;
  }
}
</style> 